package com.lh0811.forge.pserv.cgen.server.controller;

import com.lh0811.forge.dependency.basic_web.response.ServerResponse;
import com.lh0811.forge.pserv.cgen.server.component.CodeGenConfig;
import com.lh0811.forge.pserv.cgen.server.model.dto.TableQueryResultDto;
import com.lh0811.forge.pserv.cgen.server.model.param.GeneratorCodeParam;
import com.lh0811.forge.pserv.cgen.server.model.param.SetDataBaseParam;
import com.lh0811.forge.pserv.cgen.server.model.param.TableQueryParam;
import com.lh0811.forge.pserv.cgen.server.util.MainGenUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.OutputStream;
import java.util.List;

/**
 * 代码生成器
 */
@Tag(name = "平台服务-代码逆向工具")
@RestController
@RequestMapping("/forge/plate/v1/cgen")
public class GeneratorController {

    @GetMapping("/db_info/get")
    @Operation(summary = "获取当前数据库连接信息")
    private ServerResponse getDbInfo() {
        return ServerResponse.createBySuccess(CodeGenConfig.getInstance());
    }

    @PostMapping("/db_info/set")
    @Operation(summary = "设置当前数据库连接信息")
    private ServerResponse setDbInfo(@Valid @RequestBody SetDataBaseParam param) {
        if (StringUtils.isNotBlank(param.getDbUrl())) {
            CodeGenConfig.getInstance().setDbUrl(param.getDbUrl());
        }
        if (StringUtils.isNotBlank(param.getDbUsername())) {
            CodeGenConfig.getInstance().setDbUsername(param.getDbUsername());
        }
        if (StringUtils.isNotBlank(param.getDbPassword())) {
            CodeGenConfig.getInstance().setDbPassword(param.getDbPassword());
        }
        if (StringUtils.isNotBlank(param.getPackageName())) {
            CodeGenConfig.getInstance().setPackageName(param.getPackageName());
        }
        return ServerResponse.createBySuccess("设置成功");
    }

    /*
     * 列表
     */
    @PostMapping("/list")
    @Operation(summary = "获取当前数据库数据表")
    public ServerResponse list(@Valid @RequestBody TableQueryParam param) throws Exception {
        List<TableQueryResultDto> tableQueryResultDtos = MainGenUtils.queryTableList(param.getTableName());
        return ServerResponse.createBySuccess(tableQueryResultDtos);
    }

    /**
     * 生成代码
     */
    @PostMapping("/code")
    @Operation(summary = "生成代码")
    public void code(@Valid @RequestBody GeneratorCodeParam param, HttpServletResponse response) throws Exception {
        byte[] data = MainGenUtils.generatorCode(param.getTableList());
        // 设置响应头
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=generated_code.zip");

        // 将字节数组写入响应输出流
        try (OutputStream outputStream = response.getOutputStream()) {
            outputStream.write(data);
            outputStream.flush();
        }
    }
}
